/*
 * @lc app=leetcode.cn id=54 lang=golang
 *
 * [54] 螺旋矩阵
 */

// @lc code=start

func spiralOrder(matrix [][]int) []int {
	m, n := len(matrix), len(matrix[0])
	res := make([]int, 0, m*n)
	k := 0
	for m > 0 && n > 0 {
		if k%4 == 0 {
			for i := 0; i < n; i++ {
				res = append(res, matrix[0][i])
			}
			matrix = matrix[1:][:]
			m = m - 1
		}
		if k%4 == 1 {
			for i := 0; i < m; i++ {
				res = append(res, matrix[i][n-1])

			}
			for i, _ := range matrix {
				matrix[i] = matrix[i][:n-1]
			}
			n = n - 1
		}
		if k%4 == 2 {
			for i := n - 1; i >= 0; i-- {
				res = append(res, matrix[m-1][i])
			}
			matrix = matrix[:m-1][:]
			m = m - 1
		}
		if k%4 == 3 {
			for i := m - 1; i >= 0; i-- {
				res = append(res, matrix[i][0])
			}
			for i, _ := range matrix {
				matrix[i] = matrix[i][1:]
			}
			n = n - 1
		}
		k++

	}
	return res
}

// @lc code=end
